// pages/login/index.js
import vxValidate from 'wechat-validate'
Page({
  behaviors:[vxValidate],
  data:{
    falg:true,
    captchaCode:'',//图形验证码
    captchaKey:'',//图形验证码的key
    mobile:'18917286702',//手机号
    cpaImage:'',//验证码图片
    smsCode:'246810',//短信验证码
    isParty:false, //是否第三方登录
    partyData:{}, //第三方登录信息
  },
  // 表单校验规则
  rules:{
    mobile:[
      {required:true , message:'手机号不能为空'},
      {pattern:/^1[3-9]\d{9}$/,message:'手机号格式错误'}
    ],
    captchaCode:[
      {required:true , message:'图形验证码不能为空'},
    ],
    smsCode:[
      {required:true , message:'短信验证码不能为空'},
    ]
  },
onShow(){
  // 获取图形验证码
  this.getCaptchaImage()
},
onLoad(e){
 this.url = e.url
 console.log(this.url);
},
// 获取验证码的校验 
async getyanzhengma(){
  // 表单校验
 const isOk = this.validate('mobile')
//  console.log(isOk);
 if(isOk.message === false) return wx.utils.toast(isOk.message)

 const Ok = this.validate('captchaCode')
//  console.log(Ok);
 if(Ok.valid === false) return wx.utils.toast(Ok.message)
 
//  console.log(Ok);

//  解构
 const {captchaKey,captchaCode,mobile,falg} = this.data
//  发送请求
 const {message,status} = await wx.http.post(
   '/captcha/sendSmsCaptcha',{form:{captchaKey,captchaCode,mobile}}
    )
    // console.log(message,status);
     //  修改数据更换显示样式
    this.setData({falg:false})
  if(status !== 200) return wx.utils.toast('获取验证码失败请重试')
  
  wx.utils.toast(message)
  
},

// 获取图形验证码的方法
async getCaptchaImage(){
 const {status,data} = await wx.http.get('/captcha/image')
 if(status !== 200) return wx.utils.toast()
 this.setData({
  cpaImage:data.base64,
  captchaKey:data.key
 })
},


// 倒计时的监听
countDownChange(ev){
// console.log(ev);
this.setData({
  timeData: ev.detail.seconds
})
if(ev.detail.seconds===1){
  this.setData({
    falg:true
  })
}
},

// 登录
async ButtonClick(){
  const isOk= this.validate()
  if(!isOk) return

  // console.log(isOk);
  // 发送登录请求
 const {smsCode,mobile,isParty,partyData}=this.data
 console.log(smsCode,mobile,isParty,partyData);
 const {status,data} = await wx.http.post('/passport/login',{
  form: {
     smsCode,
     mobile,
     isParty,
     partyData,
  }
})
    if(status !== 200) return wx.utils.toast('登录失败请重试')
    console.log(data);
    const app = getApp()
    // 保存token
    app.setUserToken('token',data.token)
   
    //看是否绑定的底部
    const page=[
      "/pages/home/index",
      "/pages/classify/index",
      "/pages/my/index",
      "/pages/ShoppingCart/index"
    ]

    if(page.includes(this.url)){
      wx.switchTab({
        url: this.url,
      })
    }else{
      wx.redirectTo({
        url: this.url,
      })
    }



},

})